package com.cn.demo4.common;

import java.io.*;
import java.util.List;

/**
 * @author LXJ
 */
public class IOTool {

    private static void createFile(String fileName) {
        File file = new File(MyPath.PATH.getPath());
        if (!file.exists()) {
            file.mkdirs();
        }
        File createFile = new File(file, fileName);
        try {
            createFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static File createImgPath(String fileName) {
        File file = new File(MyPath.IMG_PATH.getPath() + MyPath.LOAD_PATH.getPath());
        if (!file.exists()) {
            file.mkdirs();
        }
        File createFile = new File(file, fileName);
//        try {
//            createFile.createNewFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return createFile;
    }

    public static String read(String fileName) {

        File file = new File(MyPath.PATH.getPath(), fileName);
        StringBuilder string = new StringBuilder();
        try {
//            InputStream inputStream = new FileInputStream(file);
//            int result = 0;
//            while ((result = inputStream.read()) != -1) {
//                System.out.print((char) result);
//            }
//            Reader reader = new FileReader(file);
            InputStream inputStream = new FileInputStream(file);
            String charSet = "UTF-8";
            Reader reader = new InputStreamReader(inputStream, charSet);
            BufferedReader br = new BufferedReader(reader);
            int result = 0;
            while ((result = br.read()) != -1) {
                string.append((char) result);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return string.toString();
    }

    public static void write(String fileName, List<String> value) {
        createFile(fileName);
        File file = new File(MyPath.PATH.getPath(), fileName);
        try {
            OutputStream outputStream = new FileOutputStream(file);
            for (int i = 0; i < value.size(); i++) {
                outputStream.write(value.get(i).getBytes());
                outputStream.write(MyPath.SPLIT.getPath().getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}